package com.ebor.utils.config;

import com.ebor.utils.common.setting.RedisProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Configuration
@ConditionalOnClass({JedisCluster.class})
public class JedisClusterConfig {
    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisCluster getJedisCluster() {
        Set<HostAndPort> nodes = new HashSet<>();
        //分割出集群节点
        String[] cNodes = redisProperties.getClusterNodes().split(",");
        Arrays.stream(cNodes).filter(StringUtils::isNotBlank).forEach(c -> {
            String[] hp = c.split(":");
            nodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
        });
        JedisCluster jedisCluster = null;
        if (nodes.size() > 0) {
            JedisPoolConfig pool = new JedisPoolConfig();
            pool.setMaxIdle(redisProperties.getMaxIdle());
            pool.setMinIdle(redisProperties.getMinIdle());
            pool.setMaxTotal(redisProperties.getMaxActive());
            pool.setMaxWaitMillis(redisProperties.getMaxWait());

            // 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
            pool.setBlockWhenExhausted(true);
            // 设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
            pool.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
            // 是否启用pool的jmx管理功能, 默认true
            pool.setJmxEnabled(true);
            // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
            pool.setTestOnBorrow(true);
            //创建集群对象
            jedisCluster = new JedisCluster(nodes, redisProperties.getTimeout(), redisProperties.getCommandTimeout(),
                    redisProperties.getMaxAttempts(), redisProperties.getPassword(), pool);
        }
        return jedisCluster;
    }
}